package it.gameplanet.client.widgets;

import it.gameplanet.client.GamePlanetContext;
import it.gameplanet.client.utils.AbstractAsyncCallback;
import it.gameplanet.client.widgets.articolo.EditArticolo;
import it.gameplanet.client.widgets.articolo.ViewArticolo;
import it.gameplanet.client.widgets.support.ContextMenuLabel;
import it.gameplanet.client.widgets.support.Dialogs;
import it.gameplanet.model.Articolo;
import it.gameplanet.service.GamePlanetService;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Composite;

public class ArticoloTreeItem extends Composite {

	public ArticoloTreeItem(final Articolo articolo) {
		
		final Command modificaArticoloCommand = new Command() {
			  public void execute() {
				  GamePlanetContext.setContentPanel(new EditArticolo(articolo));				  
			  }
		};
			 
		final Command eliminaArticoloCommand = new Command() {
			  public void execute() {
			    
			    GamePlanetService.Utils.getGamePlanetServiceAsync().eliminaArticolo(articolo, new AbstractAsyncCallback<Void>() {

					@Override
					public void onSuccess(Void result) {
						Dialogs.showMessage("Articolo "+articolo.getNome()+ " cancellato con successo");
						GamePlanetContext.getArticoliTree().reload();
					}
				});
			  }
		};
			 
		Map<String, Command> menu = new HashMap<String, Command>();
		menu.put("Modifica Articolo", modificaArticoloCommand);
		menu.put("Elimina Articolo", eliminaArticoloCommand);

		ContextMenuLabel label = new ContextMenuLabel(articolo.getNome(), menu);
		label.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				
				GamePlanetContext.setContentPanel(new ViewArticolo(articolo));
			}
			
		});
		
		initWidget(label);
	}
}
